<template>
  <div style="margin-right: 250px">
    <el-input style="width: 260px" v-model="username" placeholder="请输入用户名" clearable></el-input>
    <el-input style="width: 260px" v-model="level" placeholder="请输入等级" clearable></el-input>
    <el-button style="margin-left: 10px" type="primary" @click="load"><el-icon><Search/></el-icon>查询</el-button>
    <el-button @click="handleAdd" type="primary"><el-icon><Plus/></el-icon>新增</el-button>
  </div>
  <el-table :data="state.tableData" stripe style="width: 100%">
    <el-table-column prop="id" label="ID" width="180" />
    <el-table-column prop="username" label="用户名" />
    <el-table-column prop="level" label="等级" />
    <el-table-column prop="spend" label="累计花费" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleEdit(scope.row)"><el-icon><Edit /></el-icon>编辑</el-button>
        <el-popconfirm title="确认删除吗？" @confirm="handleDelete(scope.row.id)">
          <template #reference>
            <el-button link type="danger" ><el-icon><Delete /></el-icon>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin: 10px 0">
    <el-pagination
        :background = "true"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        large
        :disabled="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="dialogFormVisible" title="用户信息" width="40%">
    <el-form :model="state.form" :rules="state.rules" ref="ruleFormRef" style="width: 85%" label-width="120px">
      <el-form-item label="用户名"  prop="username">
        <el-input v-model="state.form.username" autocomplete="off" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="等级"  prop="level">
        <el-input v-model="state.form.level" autocomplete="off" placeholder="请输入等级"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {Edit, Delete, Plus, Search} from '@element-plus/icons-vue'
import {getCurrentInstance, reactive, ref} from "vue";
import request from "../request.js";
import {ElMessage, ElNotification} from "element-plus";
const {proxy} = getCurrentInstance()

const checkEmail = (rule, value, callback) =>{
  console.log(value)
  if(!/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(value)){
    return callback(new Error('邮箱格式错误'))
  }
  callback()
}
const state = reactive({
  tableData:[],
  form:{},
  rules:{
    username:[
      {required:true, message:'请输入用户名', trigger:'blur'},
      {min:2, message: '最少输入两位', trigger:'blur'}
    ],
    address:[
      {required:true, message:'请输入地址', trigger:'blur'},
      {max:255, message: '最多255个字符', trigger:'blur'}
    ],
    email:[
      { validator: checkEmail, trigger: 'blur'}
    ]
  }
})

const currentPage = ref(1)
const pageSize = ref(1)
const total = ref(0)
const username = ref('')
const level = ref('')

const load = () =>{
  request.get("/user2/page", {
    params:{
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      username: username.value,
      level: level.value
    }
  }).then(res => {
    if(res.code==='200'){
      state.tableData = res.data.list
      total.value = res.data.total
      //console.log(state.tableData)
    }
  })
}
load()

const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  load()
}

const dialogFormVisible = ref(false)
const handleAdd = () => {
  dialogFormVisible.value = true
  state.form = {} //初始化数据
}

const handleEdit = (row) => {
  dialogFormVisible.value = true
  state.form = JSON.parse(JSON.stringify(row))
}

const save = () => {
  proxy.$refs.ruleFormRef.validate((valid) => {
    if(valid){
      //console.log(state.form)
      if(state.form.id){//id存在为编辑
        request.put("/user2", state.form).then(res => {
          if(res.code==='200'){
            ElNotification({
              type:'success',
              message:'保存成功'
            })
            dialogFormVisible.value = false
            load()
          }else{
            ElNotification.error(res.msg);
          }
        })
      }else{//新增
        state.form.password = "123"
        request.post("/user2", state.form).then(res => {
          if(res.code=='200'){
            ElNotification({
              type:'success',
              message:'保存成功'
            })
            dialogFormVisible.value = false
            load()
          }else{
            ElMessage.error(res.msg);
          }
        })
      }
    }
  })
}

const handleDelete = (id) => {
  request.delete("/user2/" + id).then(res => {
    if(res.code==='200'&&res.data) {
      ElNotification.success("删除成功")
    }else{
      ElMessage.error("删除失败")
    }
    load()
  })
}



</script>